package net.alche.sdd.fatis.macro;

import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import net.alche.al.util.AC;
import net.alche.sdd.fatis.SddFatisMacro;
@SuppressWarnings("all")
public class SddFatisMacroForEach {
  Object obj;
  SddFatisMacro macroPar;
  public int lv = -1;
  String itemName = "";
  String open = "";
  String close = "";
  String separator = "";
  String sql = "";
  String itemSql = "";

  public SddFatisMacroForEach(SddFatisMacro macro, Object obj) {
    this.obj = obj;
    this.macroPar = macro;
  }

  public void addLine(String str) {
    itemSql += " " + str.trim();
  }

  public String getSql() {
    String line = itemSql;
    String toSql = "";
    List<String> list = AC.reg.matchers("(#|\\$)\\{[\\w\\.\\[\\]\\ ]+\\}", line);
    if (list != null && !list.isEmpty()) {
      if (ArrayUtil.isArray(obj)) {
        Object[] objs = (Object[]) obj;
        for (Object item : objs) {
          toSql = getSqlParam(toSql, line, list, item);
        }
      } else if (obj instanceof List ls) {
        for (Object item : ls) {
          toSql = getSqlParam(toSql, line, list, item);
        }
      }
    }
    return " " + open + toSql + close;
  }

  public String getSqlParam(String toSql, String line, List<String> macroList, Object item) {
    for (String macro : macroList) {
      line = line.replace(macro, "?");
      String varName = macroPar.getSqlMacroName(macro);
      String[] vp = varName.split("\\.");
      if (vp.length == 1) {
        if (varName.equals(itemName))
          macroPar.addPrepared(item);
        else {
          macroPar.addPrepared(macroPar.getParam(varName));
        }
      } else {
        if (vp[0].equals(itemName)) {
          macroPar.addPrepared(BeanUtil.getFieldValue(item, vp[1]));
        } else {
          Object obj = macroPar.getParam(varName);
          if (obj == null) {
            macroPar.addPrepared(null);
          }else{
            macroPar.addPrepared(BeanUtil.getFieldValue(obj, vp[1]));
          }
        }
      }
    }
    if (!toSql.equals(""))
      toSql += separator;
    toSql += line;
    return toSql;
  }

  public void setMap(Map<String, String> attrMp) {
    if (attrMp.containsKey("item")) {
      itemName = attrMp.get("item");
    }
    if (attrMp.containsKey("open")) {
      open = attrMp.get("open");
    }
    if (attrMp.containsKey("close")) {
      close = attrMp.get("close");
    }
    if (attrMp.containsKey("separator")) {
      separator = attrMp.get("separator");
    }
  }
}
